import aiohttp
import asyncio

'''
    利用协程：
        这样，请求是三个同时发送，而不是等一个发送下载完成后再发送下一个
        提高效率
'''


async def fetch(session, url):
    print("发送请求：", url)
    async with session.get(url, verify_ssl=False) as response:
        content = await response.content.read()
        file_name = url.rsplit('=')[-1]
        with open(file_name, 'wb') as f:
            f.write(content)
        print("保存图片：", file_name)


async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            'https://img1.baidu.com/it/u=1582561242,3081605357&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=965',
            'http://img0.baidu.com/it/u=3151399787,3583857899&fm=253&app=138&f=JPEG?w=800&h=968',
            'http://img0.baidu.com/it/u=2059022366,2634566397&fm=253&app=138&f=JPEG?w=800&h=962'
        ]
        tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
        await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())
